package com.wanfan.wanfanBrush.common;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池的单例模式
 *
 * @author 晚饭
 * @date 2025/06/10
 */

public class SingletonThreadPool {

    //使用volatile保证线程安全，可见性
    private static volatile ThreadPoolExecutor threadPoolExecutor;

    //私有构造函数，防止外部实例化
    private SingletonThreadPool() {
    }

    //获取实例
    public static ThreadPoolExecutor getInstance() {
        if (threadPoolExecutor == null) {
            synchronized (SingletonThreadPool.class) {
                if (threadPoolExecutor == null) {
                    threadPoolExecutor = new ThreadPoolExecutor(
                            4                   //核心线程数 服务器是2核2G轻量级，使用CPU核心数的两倍作为核心线程
                            , 10                //最大线程数，选用10条线程做最大线程数
                            , 60L               //线程空闲存活时间 当线程池中使用的线程超过了核心线程数后60s没有任何任务自动销毁
                            , TimeUnit.SECONDS  //存活时间单位
                            , new LinkedBlockingDeque<>(1000)   //阻塞队列容量
                            , new ThreadPoolExecutor.CallerRunsPolicy() //拒绝策略，由调用线程处理任务
                    );
                }
            }
        }
        return threadPoolExecutor;
    }

    //关闭线程池
    public static void shutdown() {
        if (threadPoolExecutor != null && !threadPoolExecutor.isShutdown()) {
            threadPoolExecutor.shutdown();
        }
    }
}
